package com.piece.core.framework.util.message;

import com.piece.core.framework.util.string.StringUtil;
import lombok.extern.slf4j.Slf4j;
import java.util.Iterator;
import java.util.Map;

/**
 * 消息发送监听工厂
 */
@Slf4j
public class MessageFactory {

    private Map<String, Message> messageMap;

    private Map<String, MessageOperator> messageOperatorMap;

    private Message defaultMessage;

    private MessageOperator defaultOperator;

    public MessageFactory(Map<String, Message> messageMap, Map<String, MessageOperator> messageOperatorMap) {
        log.info("加载 MessageFactory...");
        this.messageMap = messageMap;
        this.messageOperatorMap = messageOperatorMap;
        this.initMessage();
        this.initMessageOperator();
    }

    private void initMessage() {
        if (null != this.messageMap) {
            Iterator<Map.Entry<String, Message>> it = this.messageMap.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, Message> entry = it.next();
                log.info("加载 MessageFactory --> {}", entry.getKey());
                if (entry.getValue().isDefault() || null == this.defaultMessage) {
                    this.defaultMessage = entry.getValue();
                }
            }
        }
    }

    private void initMessageOperator() {
        if (null != this.messageOperatorMap) {
            Iterator<Map.Entry<String, MessageOperator>> it = this.messageOperatorMap.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, MessageOperator> entry = it.next();
                log.info("加载 MessageFactory --> {}", entry.getKey());
                if (null == this.defaultOperator) {
                    this.defaultOperator = entry.getValue();
                }
            }
        }
    }

    public void addMessageHook(String name, Message message) {
        this.messageMap.put(name, message);
    }

    public void addMessageOperatorHook(String name, MessageOperator operator) {
        this.messageOperatorMap.put(name, operator);
    }

    public Message get() {
        return this.defaultMessage;
    }

    public Message get(String message) {
        if (StringUtil.isEmpty(message)) return get();
        return this.messageMap.get(message);
    }

    public MessageOperator getOperator() {
        return this.defaultOperator;
    }

    public MessageOperator getOperator(String operator) {
        if (StringUtil.isEmpty(operator)) return getOperator();
        return this.messageOperatorMap.get(operator);
    }
}
